import * as THREE from '../../build/three.module.js';

// 常量
const shperes = [];

// 全局变量
// 鼠标位置
let mouseX = 0, mouseY = 0;
let halfWindowWidth = innerWidth / 2,
    halfWindowHeight = innerHeight / 2;

// 盒子贴图
const path = '../../textures/cube/pisa/';
const format = '.png';
const url = [
  path + 'px' + format, path + 'nx' + format,
  path + 'py' + format, path + 'ny' + format,
  path + 'pz' + format, path + 'nz' + format,
];

// 反射贴图
const reflectionMap = new THREE.CubeTextureLoader().load( url );
reflectionMap.format = THREE.RGBAFormat;

// 场景
const scene = new THREE.Scene();
scene.background = reflectionMap;

// 相机
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 1, 100000);
camera.position.z = 3200;

// 渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

// 构建自由移动的球体
const geo = new THREE.SphereBufferGeometry(100, 32, 16);
const mtl = new THREE.MeshBasicMaterial({ color: 0xffffff, envMap: reflectionMap });

for(let i = 0; i < 500; i += 1) {
  const mesh = new THREE.Mesh(geo, mtl);

  mesh.position.set(
    Math.random() * 10000 - 5000,
    Math.random() * 10000 - 5000,
    Math.random() * 10000 - 5000
  );

  mesh.scale.x = mesh.scale.y = mesh.scale.z =  Math.random() * 3 + 1;

  scene.add(mesh);

  shperes.push(mesh);
}

// 渲染函数
const render = () => {
  const time = new Date() * 0.0001;

  for(let i = 0; i < shperes.length; i += 1) {
    const mesh = shperes[i];

    mesh.position.x = 5000 * Math.sin(time + i );
    mesh.position.y = 5000 * Math.cos(time + i * 1.1);
  }

  camera.position.x += (- mouseX - camera.position.x) * 0.05;
  camera.position.y += (mouseY - camera.position.y) * 0.05;

  camera.lookAt(scene.position);

  renderer.render(scene, camera);
}

// 驱动
const animate = () => {
  requestAnimationFrame(animate);

  render();
}
animate();

// 事件监听
const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  halfWindowWidth = innerWidth / 2;
  halfWindowHeight = innerHeight / 2;

  renderer.setSize(innerWidth, innerHeight);
}
handleWindowResize();
window.addEventListener('resize', handleWindowResize, false);

const handleMousemove = e => {
  mouseX = (e.clientX - halfWindowWidth) * 10;
  mouseY = (e.clientY - halfWindowHeight) * 10;
}
window.addEventListener('mousemove', handleMousemove, false);
